package wqh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wqh.domain.DtDevice;
import wqh.domain.DtMapPos;
import wqh.domain.DtSensor;
import wqh.pojo.MapRet;
import wqh.pojo.SelectIPandChannelCondition;
import wqh.service.DtDeviceService;
import wqh.service.DtMapPosService;
import wqh.service.DtSensorService;

import java.util.List;

/**
 * Created by devts on 2016/11/30.
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/water/dt_map_pos")
public class DtMapPosController {

    @Autowired
    private DtMapPosService mapPosService;

    @Autowired
    private DtDeviceService deviceService;

    @Autowired
    private DtSensorService sensorService;

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(@RequestBody DtMapPos mapPos)
    {
        try {
            if(mapPosService.findRecordByClass(mapPos).size() != 0){
                return MapRet.SQL_INSERT_ERROR();
            }
            mapPosService.insertRecord(mapPos);
            DtDevice  device = deviceService.findAllById(mapPos.getDevice_id());
            DtSensor sensor = sensorService.findByDeviceIdAndCode(device.getId(),mapPos.getSensor_code());
            sensor.setGeo_id(mapPos.getGeo_building_id());
            sensorService.updateById(sensor);
            return MapRet.SQL_INSERT_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_INSERT_ERROR();
        }
    }

    @RequestMapping(value = "/update1",method = RequestMethod.POST)
    public Object update1(@RequestBody  DtMapPos mapPos)
    {
        try {
            mapPosService.updateRecordByClass(mapPos);
            return MapRet.SQL_UPDATE_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_UPDATE_ERROR();
        }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object delete(@RequestParam(value = "id",required = true) int id)
    {
        try {
            mapPosService.deleteById(id);
            return MapRet.SQL_DELETE_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_DELETE_ERROR();
        }
    }

    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    public Object getAll(@RequestParam(value = "geo_building_id",required = true) int geo_building_id)
    {
        try {
            List<DtMapPos> mapPosList = mapPosService.findRecordByGeoID(geo_building_id);
            if(mapPosList.size() == 0) return MapRet.SQL_ERROR();
            else return MapRet.DATA(mapPosList);
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_ERROR();
        }
    }

}
